const koa = require('koa')
const koaStatic = require('koa-static')
const http = require('http')
const koaJson = require('koa-json')
const koaBody = require('koa-body')
const koaJwt = require('koa-jwt')
const koaCors = require('koa-cors')
const koaParameter = require('koa-parameter')
const { connect } = require('./db/index.js') // 引入数据库连接
connect() // 连接数据库

const chatWebsocket = require('./routes/chat-websocket.js')
const userRouter = require('./routes/user.js')

const app = new koa();
app.use(koaCors())
app.use(koaStatic('public'));
app.use(koaJson());
app.use(koaBody());
app.use(koaParameter(app));

app.use((ctx, next) => {
    return next().catch((err) => {
        if (err.status === 401) {
            ctx.status = 401;
            ctx.body = 'Protected resource, use Authorization header to get access\n';
        } else {
            throw err;
        }
    })
})

app.use(koaJwt({
    secret: '9527',
}).unless({ // 配置白名单
    path: [
        /\/api\/register/,
        /\/api\/login/
    ]
}))

app.use(userRouter.routes(), userRouter.allowedMethods())

const server = http.createServer(app.callback());
server.on('upgrade', chatWebsocket.upgrade.bind(chatWebsocket))
const port = 8080
server.listen(port, () => {
    console.log(`listening on port ${port}`);
});
